package com.eternal.util.user.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.eternal.Exception.ResultEnum;
import com.eternal.Exception.ResultException;
import com.eternal.login.shiro.ShiroCryptographyUtil;
import com.eternal.permission.entity.UserRole;
import com.eternal.util.user.entity.UserInfo;
import com.eternal.util.user.dao.UserInfoMapper;
import com.eternal.util.user.service.UserInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.eternal.util.user.vo.UserVo;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户基础表 服务实现类
 * </p>
 *
 * @author Eternal
 * @since 2018-08-26
 */
@Service
@Primary
@Transactional
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Override
    public UserInfo getUserInfo(String userId) {
        UserInfo userInfo = this.baseMapper.selectById(userId);
        return userInfo;
    }

    @Override
    public UserInfo getUserInfoByopenId(String openId) {
        Wrapper<UserInfo> wrapper = new EntityWrapper<>();
        wrapper.where("open_id={0}", openId);
        UserInfo userInfo = new UserInfo();
        UserInfo userInfo1 = userInfo.selectOne(wrapper);
        if (null == userInfo1) {
            throw new ResultException(ResultEnum.USER_UNBOUND_OPENID, openId);
        }
        return userInfo1;
    }

    @Override
    public UserVo getUserAllInfo(String userId) {
        UserVo userVo = this.baseMapper.selectUserAllInfo(userId);
        return userVo;
    }

    @Override
    public boolean registerUser(UserInfo userInfo) {
        UserInfo userInfo1 = userInfo.selectById();
        if (null == userInfo1) {
            userInfo.setIsAvailable("1");
            userInfo.setPassword(ShiroCryptographyUtil.encryptMD5(userInfo.getPassword(), userInfo.getUserId(), 1));
            userInfo.setOrgId("000000");
            boolean insert = userInfo.insert();
            if (insert){
                UserRole userRole = new UserRole();
                userRole.setUserId(userInfo.getUserId());
                userRole.setRoleId("admin");
                userRole.insert();
            }

            return insert;
        }

        throw new ResultException(ResultEnum.USER_EXIST);

    }

    @Override
    public boolean queryIsUser(String userId) {
        Wrapper<UserInfo> wrapper = new EntityWrapper<>();
        wrapper.where("userId={0}", userId);
        int i = selectCount(wrapper);
        return i > 0 ? false : true;
    }
}
